//index.js

const requestPostLanderToken = require('../../utils/request.js').requestPostLanderToken
const requestToGetHouseBook = require('../../utils/request.js').requestToGetHouseBook
const requestToDeleteHouse = require('../../utils/request.js').requestToDeleteHouse
const requestToGetBill = require('../../utils/request.js').requestToGetBill

const toAddHousePage = require('../../utils/wx-navigate.js').toAddHousePage
const toAddBookPage = require('../../utils/wx-navigate.js').toAddBookPage
const toBookDeatilPage = require('../../utils/wx-navigate.js').toBookDeatilPage
const toBillDeatilPage = require('../../utils/wx-navigate.js').toBillDeatilPage
const toRecordPage = require('../../utils/wx-navigate.js').toRecordPage
const toAccountPage = require('../../utils/wx-navigate.js').toAccountPage
const toAdvicePage = require('../../utils/wx-navigate.js').toAdvicePage


const wxPromise = require('../../utils/wx-promisify.js')
const saveToken = require('../../utils/util-token.js').saveToken

const showDialog = require('../../utils/util.js').showDialog
const showDialogMsg = require('../../utils/util.js').showDialogMsg
const formatTimeYM = require('../../utils/util.js').formatTimeYM
const billSortByMonth = require('../../utils/util.js').billSortByMonth
const getMonthIndex = require('../../utils/util.js').getMonthIndex

const requestToGetAccount = require('../../utils/request.js').requestToGetAccount

//获取应用实例
const app = getApp()

Page({
  data: {
    page:"index",
    tabArray: [{ prop: '', label: '账本' }, { prop: '', label: '待收房租' }],
    currentIndex:0,
    userInfo: {},
    bookList:[],
    billList: [],
    currentMonthBill:{},
    showHeader:true,
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    startPosition:null,
    balance:"0"
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function () {


    let month = new Date().getMonth() + 1
    let currentMonthBill = { month: month, count: 0, money: 0 }
    this.setData({
      currentMonthBill: currentMonthBill
    })
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse){
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }


    this.toGetData()
    app.updateIndexPageData = this.toGetData
  },

  toGetData(){
    requestToGetHouseBook(res => {
      console.log(res)
      this.setData({
        bookList: res.list
      })
    })

    requestToGetBill("","",res => {
      
      let list = billSortByMonth(res.list)
      // console.log(list)
      this.setData({
        billList: list
      })
    })

    requestToGetBill("", "SUCCESS&&CLOSED", res => {
      console.log(res)
      let list = billSortByMonth(res.list)

      let currentMonth = formatTimeYM(new Date())
      let currentIndex = getMonthIndex(currentMonth, list)
      let month = new Date().getMonth()+1
      if (currentIndex>=0){
        let currentMonthBill = { month: month, count: list[currentIndex].billList.length, money: list[currentIndex].haspaymoney }

        this.setData({
          currentMonthBill: currentMonthBill
        })
      }
      
    })
    

    requestToGetAccount(res => {
      console.log(res)
      this.setData({
        balance: res.balance
      })
    })
  },


  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  getLanderToken:function(){
    wxPromise.getUserInfo().then(res=>{
      this.setData({
        userInfo: res.userInfo,
      })
      return wxPromise.login()
    }).then(res => {
      requestPostLanderToken(res.code, this.data.userInfo,res=>{
        saveToken(res.token)
        app.globalData.token = res.token
        app.updateIndexPageData()
      })
    })
    
    console.log("getLanderToken")
  },

  catchBottomItemTab: function (e){
    switch (e.detail.tabItem) {
      case -1://
        console.log('点击了新建账本')

        let token = app.globalData.token
        console.log(token)
        if (token) {
          toAddHousePage()
        } else {
          wx.showToast({
            title: "请重新登录",
            icon: 'none',
            mask: true,
          })
        }
        
        break;
      case 0://
        console.log('点击了租房账本')
        this.setData({
          page:"index",
          currentIndex:0,
        })
        break;
      case 1://
        console.log('点击了我的')
        this.setData({
          page: "me",
          
        })
        break;
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.toGetData()
  },

  bindBookItemTab:function(e){
    if (e.currentTarget.dataset.book.book){
      toBookDeatilPage(e.currentTarget.dataset.book)
    }else{
      toAddBookPage(e.currentTarget.dataset.book)
    }
  },
  payTabClick(e) {
    this.setData({
      currentIndex: e.detail.currentIndex
    })

  },

  bindbillItemTab: function (e) {
    toBillDeatilPage(e.currentTarget.dataset.bill)
  },

  bindheaderitemtap: function (e) {
    toRecordPage()
  },

  itemTouchstart: function (e) {
    // let bookid = e.currentTarget.dataset.bookid
    // let address = e.currentTarget.dataset.address
    let touchhid = e.currentTarget.dataset.houseid
    let touchPosition = e.touches[0]
    this.setData({
      startPosition: touchPosition,
    })
  },

  itemTouchend: function (e) {
    let touchPosition = e.changedTouches[0]
    let startX = this.data.startPosition.clientX
    let startY = this.data.startPosition.clientY
    let endX = touchPosition.clientX
    let endY = touchPosition.clientY

    // if (startY - endY > 50 || startY - endY < -50) {
    //   return
    // }
    if (startY - endY > 50) {
      //下滑：大于50px以上
      // console.log('左滑')

      this.setData({
        showHeader: false,
      })
    }

    if (startY - endY < -50) {
      //上滑：小于-50px以上
      // console.log('右滑')
      this.setData({
        showHeader: true,
      })
    }
  },

  bindonerowitemtap:function(e){
    switch (e.currentTarget.dataset.id){
      case "我的账户":
        toAccountPage()
        console.log('sbsb')
        break;
      case "意见反馈":
        toAdvicePage()
        console.log('111sbsb')
        break;
    }
    
  },

  bindleftitemtap: function (e) {
    
    console.log(e.detail.house_id)

    
    if (e.detail.book) {
      showDialogMsg("请先将租客退房后再删除账本")
    } else {
      showDialog("确认删除账本", "删除账本之后，该账本中的所有信息和账单记录都将被删除", () => {
        requestToDeleteHouse(e.detail.house_id, () => {

          this.toGetData()
          console.log('删除成功')
        })
        
      })
    }
  },

 

})
